package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/config"
	"yanxue_ai_go/pkg/common/initialize"
	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/middleware"
	"yanxue_ai_go/services/rag/internal/handler"
	"yanxue_ai_go/services/rag/internal/service"
)

func main() {
	// 初始化服务依赖（RAG服务包括MongoDB）
	initResult, err := initialize.InitializeService("rag")
	if err != nil {
		logger.Logger.Fatal("Failed to initialize service", zap.Error(err))
	}
	defer initResult.Cleanup()

	// 初始化RAG服务
	ragService := service.NewRAGService()

	// 初始化路由
	router := setupRouter(initResult.Config, ragService)

	// 启动服务器
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", 8083), // RAG服务端口
		Handler:      router,
		ReadTimeout:  time.Duration(initResult.Config.Server.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(initResult.Config.Server.WriteTimeout) * time.Second,
		IdleTimeout:  time.Duration(initResult.Config.Server.IdleTimeout) * time.Second,
	}

	// 启动服务器并等待关闭信号
	go func() {
		logger.Logger.Info("RAG service started",
			zap.String("addr", server.Addr),
			zap.String("env", initResult.Config.App.Environment))

		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Logger.Fatal("Failed to start server", zap.Error(err))
		}
	}()

	// 优雅关闭
	shutdownHandler := initialize.NewGracefulShutdown("rag", server, initResult.Cleanup)
	if err := shutdownHandler.Wait(); err != nil {
		logger.Logger.Error("Shutdown error", zap.Error(err))
	}
}

func setupRouter(cfg *config.Config, ragService *service.RAGService) *gin.Engine {
	if cfg.App.Environment == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	router := gin.New()

	// 添加中间件
	router.Use(middleware.LoggerMiddleware())
	router.Use(middleware.RecoveryMiddleware())
	router.Use(middleware.CORSMiddleware(
		cfg.Security.CORSAllowedOrigins,
		cfg.Security.CORSAllowedMethods,
		cfg.Security.CORSAllowedHeaders,
	))

	// 健康检查
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "healthy", "service": "rag"})
	})

	// RAG API路由
	h := handler.NewRAGHandler(ragService)
	api := router.Group("/api/v1")
	{
		// 知识库管理
		kb := api.Group("/knowledge-bases")
		{
			kb.POST("", h.CreateKnowledgeBase)
			kb.GET("", h.ListKnowledgeBases)
			kb.GET("/:id", h.GetKnowledgeBase)
			kb.PUT("/:id", h.UpdateKnowledgeBase)
			kb.DELETE("/:id", h.DeleteKnowledgeBase)
		}

		// 文档管理
		docs := api.Group("/documents")
		{
			docs.POST("", h.CreateDocument)
			docs.GET("", h.ListDocuments)
			docs.GET("/:id", h.GetDocument)
			docs.PUT("/:id", h.UpdateDocument)
			docs.DELETE("/:id", h.DeleteDocument)
			docs.POST("/:id/chunks", h.ChunkDocument)
		}

		// 向量搜索
		search := api.Group("/search")
		{
			search.POST("/semantic", h.SemanticSearch)
			search.POST("/hybrid", h.HybridSearch)
			search.POST("/similar", h.SimilaritySearch)
		}

		// RAG问答
		qa := api.Group("/qa")
		{
			qa.POST("/ask", h.AskQuestion)
			qa.POST("/chat", h.ChatWithKnowledge)
			qa.GET("/history/:session_id", h.GetChatHistory)
		}

		// 向量化
		embedding := api.Group("/embedding")
		{
			embedding.POST("/text", h.EmbedText)
			embedding.POST("/batch", h.BatchEmbed)
		}
	}

	return router
}
